package com.ciwong.epaper.modules.wordlist.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.evaluate.ui.SentenceRepeatActivity;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.wordlist.WordListReadActivity;
import com.ciwong.epaper.modules.wordlist.bean.PageListBean;
import com.ciwong.epaper.modules.wordlist.bean.WordDownloadInfo;
import com.ciwong.epaper.modules.wordlist.util.WordBookDownload;
import com.ciwong.epaper.modules.wordlist.util.WordOnPlayListener;
import com.ciwong.epaper.modules.wordlist.util.WorkBookJumpManager;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.widget.ColorationTextView;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.evaluate.BaseFrameLayout;
import com.ciwong.epaper.widget.evaluate.WorkViewPager;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 单词跟读详情view
 */
public class WordBookWordDetailView extends BaseFrameLayout {
    private static final String TAG = "ExerciseBookWordDetailV";
    private WorkViewPager viewPager;

    public List<PageListBean> wordDatas = new ArrayList<>();

    private int currentPageIndex;

    private LayoutInflater inflater;

    private OnPageSelectChangeListener mSelelectChangeListener;
    public ViewPageAdapter mAdapter;
    private Activity mContext;
    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    public WordBookWordDetailView(Context context) {
        super(context);
        init();
    }

    public WordBookWordDetailView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public WordBookWordDetailView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        viewPager = new WorkViewPager(getContext());
        addView(viewPager);
        viewPager.setLayoutParams(
                new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                        ViewGroup.LayoutParams.FILL_PARENT));
        inflater = LayoutInflater.from(getContext());
        viewPager.setCanScroll(true);
        viewPager.setVerticalScrollBarEnabled(false);
        viewPager.setHorizontalScrollBarEnabled(false);
        mAdapter = new ViewPageAdapter();
        viewPager.setAdapter(mAdapter);

        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (mSelelectChangeListener != null) {
                    mSelelectChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                currentPageIndex = position;
                if (mSelelectChangeListener != null) {
                    mSelelectChangeListener.onPageSelected(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }


    /**
     * 设置播放图标的显示状态
     *
     * @param isShow
     */
    public void setPlayBtnState(ImageView imageView, boolean isShow) {
        Log.e(TAG, "setPlayBtnState: setPlayBtnState");
        if (isShow) {
            Drawable drawable = imageView.getBackground();
            if (drawable != null && drawable instanceof AnimationDrawable) {
                ((AnimationDrawable) drawable).start();
            }

        } else {
            Drawable drawable = imageView.getBackground();
            if (drawable != null && drawable instanceof AnimationDrawable) {
                ((AnimationDrawable) drawable).stop();
            }
            imageView.setBackgroundDrawable(null);
            imageView.setBackgroundResource(R.drawable.play_animation_ls_exercise);
        }
    }


    /**
     * 设置显示数据源
     *
     * @param
     * @param words
     * @param currPage
     */
    public void setData(Activity context, final List<PageListBean> words, int currPage, boolean isRefresh, boolean serviceExpired) {
        mContext = context;
        this.serviceExpired = serviceExpired;
        if (isRefresh) {
            wordDatas.clear();
        }
        wordDatas.addAll(words);
        mAdapter.notifyDataSetChanged();
        if (isRefresh) {
            currentPageIndex = currPage;
            viewPager.setCurrentItem(currPage);
        }


    }


    private int pageSize() {
        return wordDatas == null ? 0 : wordDatas.size();
    }

    /**
     * 下一页
     */
    public void next() {
        currentPageIndex++;
        if (currentPageIndex >= pageSize()) {
            currentPageIndex = pageSize() - 1;
            return;
        }
        animTo(currentPageIndex);
    }

    /**
     * 下一页
     */
    public void pre() {
        if (currentPageIndex >= 1) {
            currentPageIndex--;
            animTo(currentPageIndex);
        }

    }


    /**
     * 滚动到指定界面
     *
     * @param index 索引
     */
    public void animTo(int index) {
        currentPageIndex = index;
        viewPager.setCurrentItem(index, true);
    }


    private UnitSpeechHolder getUnitSpeechHolder(int position) {
        View cur = viewPager.findViewWithTag(position);
        if (cur == null) {
            return null;
        }
        UnitSpeechHolder holder = (UnitSpeechHolder) cur
                .getTag(R.string.speech_tag_holder);
        return holder;
    }


    /**
     * 页码发生变化
     *
     * @param listener
     */
    public void setOnPageSelectChangeListener(
            OnPageSelectChangeListener listener) {
        mSelelectChangeListener = listener;
    }


    public class ViewPageAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return wordDatas == null ? 0 : wordDatas.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            container.removeView((RelativeLayout) object);
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final UnitSpeechHolder holder = new UnitSpeechHolder();
            holder.spokenContainer = inflater.inflate(R.layout.exercise_unit_speech,
                    null);
            container.addView(holder.spokenContainer);
            holder.unitPic = (ImageView) holder.spokenContainer
                    .findViewById(R.id.unitPic);
            holder.ivNativeAudio = (ImageView) holder.spokenContainer
                    .findViewById(R.id.iv_original_audio);
            holder.ivRecordAudio = (ImageView) holder.spokenContainer
                    .findViewById(R.id.iv_record_audio);
            holder.ivLoading = (ImageView) holder.spokenContainer
                    .findViewById(R.id.iv_loading);
            holder.ivRecordLoading = (ImageView) holder.spokenContainer.findViewById(R.id.iv_record_loading);
            holder.speech = holder.spokenContainer
                    .findViewById(R.id.speech);
            holder.symbol = (TextView) holder.spokenContainer
                    .findViewById(R.id.symbol);
            holder.tvExampleSentence = (TextView) holder.spokenContainer
                    .findViewById(R.id.tv_example_sentence);
            holder.pretations = (TextView) holder.spokenContainer
                    .findViewById(R.id.pretations);
            holder.sentences = (TextView) holder.spokenContainer
                    .findViewById(R.id.sentences);
            holder.recordScore = (TextView) holder.spokenContainer
                    .findViewById(R.id.tv_record_score);
            holder.tvRecordSeeScore = (TextView) holder.spokenContainer
                    .findViewById(R.id.tv_record_see_score);
            holder.tvToExercise = (TextView) holder.spokenContainer
                    .findViewById(R.id.tv_to_exercise);
            holder.vLine = holder.spokenContainer
                    .findViewById(R.id.view_line);
            holder.tvColoration = (ColorationTextView) holder.spokenContainer
                    .findViewById(R.id.coloration_tv);
            holder.spokenContainer.setTag(position);
            holder.spokenContainer.setTag(R.string.speech_tag_holder, holder);
            final PageListBean sentence = wordDatas.get(position);
            holder.speech.setText(sentence.getContent());
            final PageListBean.ResourceBean resource = sentence.getResource();
            holder.ivNativeAudio.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View v) {
                    WordDownloadInfo wordDownloadInfo = new WordDownloadInfo();
                    wordDownloadInfo.setNativeAudio(true);
                    wordDownloadInfo.setAudioUrl(resource.getAudioUrl());
                    wordDownloadInfo.setWord(sentence.getContent());
                    WordBookDownload.getInstance().startPlay(wordDownloadInfo, new WordOnPlayListener() {
                        @Override
                        public void onDownloading(WordDownloadInfo wordDownloadInfo) {
                            holder.ivNativeAudio.setVisibility(GONE);
                            holder.ivLoading.setVisibility(VISIBLE);
                            Animation loadAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_anim);
                            holder.ivLoading.startAnimation(loadAnimation);
                        }

                        @Override
                        public void onDownloadCompelted(WordDownloadInfo wordDownloadInfo) {
                            holder.ivLoading.clearAnimation();
                            holder.ivLoading.setVisibility(GONE);
                            holder.ivNativeAudio.setVisibility(VISIBLE);
                        }

                        @Override
                        public void onDownloadFailed(WordDownloadInfo wordDownloadInfo, Throwable e) {
                            if (!NetworkUtils.isOnline()) {
                                WordBookWordDetailView.this.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        showNativeAudioIv(holder);
                                    }
                                }, 500);

                            } else {
                                showNativeAudioIv(holder);
                            }

                        }

                        @Override
                        public void onReadPlayer(long l, Object o) {

                        }

                        @Override
                        public void onPlayStart(Object o) {
                            setPlayBtnState((ImageView) v, true);
                        }

                        @Override
                        public void stop(Object o) {
                            setPlayBtnState((ImageView) v, false);
                        }

                        @Override
                        public void onError(int i, Object o) {
                        }

                        @Override
                        public void onBuffer(Object o, long l, long l1) {

                        }

                        @Override
                        public void onPlaying(long l, long l1) {

                        }
                    });

                }
            });


            if (resource != null) {
                String symbol = resource.getSymbol();
                if (symbol != null) {
                    if (!symbol.startsWith("[")) {
                        symbol = "[" + symbol;
                    }
                    if (!symbol.endsWith("]")) {
                        symbol += "]";
                    }
                    resource.setSymbol(symbol);

                }
                holder.symbol.setText(resource.getSymbol());
                holder.pretations.setText(resource.getPretatuins());
                if (resource.getSentences() != null && resource.getSentences().size() > 0 && !TextUtils.isEmpty(resource.getSentences().get(0).getText())) {
                    holder.tvExampleSentence.setVisibility(VISIBLE);
                    holder.vLine.setVisibility(VISIBLE);
                    String text = resource.getSentences().get(0).getText();
                    String replaceTxt = text.replace("\r", "\n");
                    holder.sentences.setText(replaceTxt);
                } else {
                    holder.vLine.setVisibility(GONE);
                    holder.tvExampleSentence.setVisibility(GONE);
                }
                ImageSize size = new ImageSize(DeviceUtils.getScreenWdith(),
                        R.dimen.word_pic_height);
                ImageLoader.getInstance().loadImage(
                        resource.getPicture_url(), size,
                        new ImageLoadingListener() {
                            @Override
                            public void onLoadingStarted(String s, View view) {

                            }

                            @Override
                            public void onLoadingFailed(String s, View view,
                                                        FailReason failReason) {
                                holder.unitPic.setVisibility(GONE);
                            }

                            @Override
                            public void onLoadingComplete(String s, View view,
                                                          Bitmap bitmap) {
                                if (bitmap == null) {
                                    holder.unitPic.setVisibility(GONE);
                                } else {
                                    holder.unitPic.setVisibility(VISIBLE);
                                    holder.unitPic.setImageBitmap(bitmap);
                                }


                            }

                            @Override
                            public void onLoadingCancelled(String s, View view) {

                            }
                        });
            }


            final PageListBean.RecordsBean records = sentence.getRecords();
            if (records != null) {
                if (serviceExpired) {
                    int scoreColor;
                    if (records.getScore() < SpeechUtils.SCORE_2) {
                        scoreColor = R.color.score_red;
                    } else if (records.getScore() < SpeechUtils.SCORE_4) {
                        scoreColor = R.color.score_yellow;
                    } else {
                        scoreColor = R.color.score_green_word;
                    }
                    holder.recordScore.setTextColor(mContext.getResources().getColor(scoreColor));
                    holder.recordScore.setText(records.getScore() + "");
                    if (EApplication.isSymbolColoration) {
                        EvaluateResult evaluateResult = JsonParserUtil.fromJson(records.getLines(), EvaluateResult.class);
                        holder.tvColoration.setSymbolColoration(evaluateResult, resource.getSymbol());
                    }
                    holder.tvRecordSeeScore.setVisibility(View.GONE);
                } else {
                    holder.recordScore.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
                    holder.recordScore.setText("已提交");
                    holder.recordScore.setTextSize(18);
                    String text = "查看分数";
                    SpannableString spannableString = new SpannableString(text);
                    spannableString.setSpan(new UnderlineSpan(), 0, text.length(), 0);
                    holder.tvRecordSeeScore.setText(spannableString);
                    holder.tvRecordSeeScore.setOnClickListener(new ViewOnClickListener() {
                        @Override
                        public void avertRepeatOnClick(View v) {
                            setBuyServiceDialog();
                        }
                    });
                    holder.tvRecordSeeScore.setVisibility(View.VISIBLE);
                }
                holder.ivRecordAudio.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        WordDownloadInfo wordDownloadInfo = new WordDownloadInfo();
                        wordDownloadInfo.setNativeAudio(false);
                        wordDownloadInfo.setAudioUrl(records.getAudioUrl());
                        wordDownloadInfo.setWord(sentence.getContent());
                        WordBookDownload.getInstance().startPlay(wordDownloadInfo, new WordOnPlayListener() {
                            @Override
                            public void onDownloading(WordDownloadInfo wordDownloadInfo) {
                                holder.ivRecordAudio.setVisibility(GONE);
                                holder.ivRecordLoading.setVisibility(VISIBLE);
                                Animation loadAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_anim);
                                holder.ivRecordLoading.startAnimation(loadAnimation);
                            }

                            @Override
                            public void onDownloadCompelted(WordDownloadInfo wordDownloadInfo) {
                                holder.ivRecordLoading.clearAnimation();
                                holder.ivRecordLoading.setVisibility(GONE);
                                holder.ivRecordAudio.setVisibility(VISIBLE);
                            }

                            @Override
                            public void onDownloadFailed(WordDownloadInfo wordDownloadInfo, Throwable e) {
                                if (!NetworkUtils.isOnline()) {
                                    WordBookWordDetailView.this.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            showRecordIv(holder);
                                        }
                                    }, 500);

                                } else {
                                    showRecordIv(holder);
                                }

                            }

                            @Override
                            public void onReadPlayer(long l, Object o) {
                                Log.e(TAG, "onReadPlayer: ");
                            }

                            @Override
                            public void onPlayStart(Object o) {
                                setPlayBtnState((ImageView) v, true);
                            }

                            @Override
                            public void stop(Object o) {
                                setPlayBtnState((ImageView) v, false);
                            }

                            @Override
                            public void onError(int i, Object o) {
                            }

                            @Override
                            public void onBuffer(Object o, long l, long l1) {

                            }

                            @Override
                            public void onPlaying(long l, long l1) {

                            }
                        });

                    }
                });
            }
            //去练习
            holder.tvToExercise.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterNoNetError();
                        return;
                    }
                    if (EConstants.IS_YOUKE) {
                        NewLoginDialog newLoginDialog = new NewLoginDialog(v.getContext());
                        newLoginDialog.showLoginDialog();
                        return;
                    }


                    LinkedList<PageListBean> checkedWordList = new LinkedList<>();//选择单词集合
                    checkedWordList.add(sentence);
                    WorkBookJumpManager.jumpToWordPracticeActivity(R.string.go_back, (Activity) getContext(), checkedWordList, WordListReadActivity.REQUEST_CODE_FROM_WORD_LIST_DETAIL);
                }
            });
            return holder.spokenContainer;
        }

        private void showNativeAudioIv(UnitSpeechHolder holder) {
            holder.ivLoading.clearAnimation();
            holder.ivLoading.setVisibility(GONE);
            holder.ivNativeAudio.setVisibility(VISIBLE);
            Log.e(TAG, "showNativeAudioIv: ");
        }

        private void showRecordIv(UnitSpeechHolder holder) {
            holder.ivRecordLoading.clearAnimation();
            holder.ivRecordLoading.setVisibility(GONE);
            holder.ivRecordAudio.setVisibility(VISIBLE);
            Log.e(TAG, "showRecordIv: ");
        }

        @Override
        public boolean isViewFromObject(View view, Object arg1) {
            return view == arg1;
        }

        private int mChildCount = 0;

        @Override
        public void notifyDataSetChanged() {
            mChildCount = getCount();
            super.notifyDataSetChanged();
        }

        @Override
        public int getItemPosition(Object object) {
            if (mChildCount > 0) {
                mChildCount--;
                return POSITION_NONE;
            }
            return super.getItemPosition(object);
        }
    }

    public interface OnPageSelectChangeListener {
        void onPageSelected(int index);

        void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
    }

    public static class UnitSpeechHolder {
        public View spokenContainer, vLine;

        public TextView speech;
        public ColorationTextView tvColoration;

        public ImageView unitPic, ivNativeAudio, ivRecordAudio, ivLoading, ivRecordLoading;

        public TextView symbol, pretations, sentences, recordScore, tvToExercise, tvExampleSentence, tvRecordSeeScore;

        public void copy(UnitSpeechHolder holder) {
            if (holder != null) {
                holder.speech = speech;
                holder.pretations = pretations;
                holder.tvRecordSeeScore = tvRecordSeeScore;
                holder.sentences = sentences;
                holder.spokenContainer = spokenContainer;
                holder.symbol = symbol;
                holder.unitPic = unitPic;
            }
        }

    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(mContext);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //拓展服务
                    MeJumpManager.jumpToResourseCenterH5Activity(mContext, R.string.go_back, getResources().getString(R.string.resource_center));
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

}
